﻿using Microsoft.AspNetCore.Mvc;
using News.Models;
///【2】
using News.Models.Database;
using System.Linq;

namespace News.Controllers
{
	[Route("/[action].html")]
	[Route("[controller]/[action]")]
	public class HomeController : Controller
    {

        ///【4】
        private readonly NewsContext _DataBase;
        public HomeController(NewsContext DataBase)
        {
            _DataBase = DataBase;
        }
		
		public IActionResult Index(int now_categoryid, int now_page, string search_con)
        {
            //查询 分类数据
            //           数据库上下文 所有分类结果
            var cates = _DataBase.Categories.ToList();
            //传递 分类数据
            //      参数的名字    参数的值
            ViewData["ALL_Categorys"] = cates;

            //默认展示全部新闻
            var news = _DataBase.News.ToList();

			//当初次进入网页 传入的now_categoryid默认为0 则默认显示全部
			if (now_categoryid == 0)
            {
				//设置now_categoryid为第一个分类的id
				now_categoryid = cates.FirstOrDefault().CateId;

            }
            else
            {
                //根据新闻分类id来进行搜索新闻数据
                news = _DataBase.News.Where(x => x.CateId == now_categoryid).ToList();
            }

			//当初次进入网页 传入的now_page默认为0 则默认展示第一页
			if (now_page == 0)
			{
				//设置now_page为第一页
				now_page = 1;
			}

			if (search_con != null && now_categoryid != 0) //有内容的情况下
			{
				news = _DataBase.News.Where(x => x.NewsTitle.Contains(search_con) && x.CateId == now_categoryid).ToList();
			}
			//当初次进入网页 传入的search_con默认为空 则默认不搜索
			else if (search_con != null) //有内容的情况下
			{
				news = _DataBase.News.Where(x => x.NewsTitle.Contains(search_con)).ToList();
			}

			ViewData["News"] = news;
            ViewData["NOW_CategoryID"] = now_categoryid;
            Public.NOW_CategoryID = now_categoryid;
			ViewData["NOW_Page"] = now_page;
			return View();
        }
        
		
        [HttpPost]
		public IActionResult search(Search_Content content)
        {
			var search_news = _DataBase.News.Where(x => x.NewsTitle.Contains(content.S_Content)).ToList();
            if (search_news == null)
            {
				return Content("无");
			}
            else
            {
				ViewData["News"] = search_news;
				return Content("查询成功");
			}
		}

		public IActionResult Detail(int newsID)
        {
            Public.newsid = newsID;
            //查询 分类数据
            //           数据库上下文 所有分类结果
            var __news = _DataBase.News.ToList();
            //传递 分类数据
            //      参数的名字    参数的值
            ViewData["News"] = __news;
            return View();
        }

	}
}
